<script setup>
import {
  ref,
  withDefaults,
  watch,
  onMounted,
  onBeforeUnmount,
  nextTick,
} from "vue";
import { useResizeObserver } from "@vueuse/core";
import * as echarts from "echarts";
import "echarts/theme/macarons";

const props = defineProps({
  className: {
    type: String,
    default: "chart",
  },
  width: {
    type: String,
    default: "100%",
  },
  height: {
    type: String,
    default: "100%",
  },
  options: {
    type: Object,
    default: () => {},
  },
});

let chart = null; // 取消使用代理，解决监听报错
const charts = ref(null);

useResizeObserver(charts, (entries) => {
  if (chart) {
    // console.log(chart);
    chart.resize();
  }
});

watch(
  () => props.options,
  (val) => {
    setOptions(val);
  },
  {
    deep: true,
  }
);

const initChart = () => {
  if (charts.value) {
    // console.log(charts.value);
    chart = echarts.init(charts.value);
    setOptions(props.options);
  }
};

const setOptions = (data) => {
  chart?.clear(); // 解决数据残留
  chart?.setOption(data);
};

onMounted(async () => {
  await nextTick();
  initChart();
});

onBeforeUnmount(() => {
  if (!chart) {
    return;
  }
  chart.dispose();
  chart = null;
});
</script>

<template>
  <div
    ref="charts"
    :class="className"
    :style="{ height: height, width: width }"
  />
</template>

<style lang="scss" scoped></style>
